/**
 * 智能体数据管理组合式函数
 * 提供智能体数据的响应式状态管理和操作方法
 */

import { ref, computed, onMounted } from 'vue'
import type { Agent, CreateAgentInput, AgentOperationResult } from '../types/agent'
import {
  loadAgents,
  addAgent as addAgentService,
  deleteAgent as deleteAgentService,
  exportAgentsData,
  importAgentsData,
  clearAllAgents
} from '../services/dataService'
import { useNetworkStatus } from './useNetworkStatus'

/**
 * 智能体数据管理Hook
 * @returns 返回智能体相关的响应式数据和操作方法
 */
export function useAgents() {
  /** 智能体列表响应式数据 */
  const agents = ref<Agent[]>([])
  
  /** 加载状态 */
  const loading = ref(false)
  
  /** 错误信息 */
  const error = ref<string | null>(null)
  
  /** 网络状态管理 */
  const { handleApiError, retryRequest, isOnline, networkError } = useNetworkStatus()
  
  /** 智能体总数计算属性 */
  const agentCount = computed(() => agents.value.length)
  
  /** 是否有智能体数据 */
  const hasAgents = computed(() => agents.value.length > 0)
  
  /** 按创建时间排序的智能体列表 */
  const sortedAgents = computed(() => {
    if (!agents.value || !Array.isArray(agents.value)) {
      return []
    }
    return [...agents.value].sort((a, b) => {
      return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
    })
  })
  
  /**
   * 清除错误信息
   */
  function clearError() {
    error.value = null
  }
  
  /**
   * 设置错误信息
   * @param message 错误消息
   */
  function setError(message: string) {
    error.value = message
    console.error('智能体操作错误:', message)
  }
  
  /**
   * 从服务器加载智能体数据
   */
  async function loadAgentsData(): Promise<void> {
    try {
      loading.value = true
      clearError()
      
      const result = await loadAgents()
      agents.value = result
    } catch (err) {
      const networkErr = handleApiError(err, loadAgentsData)
      setError(networkErr.message)
      console.error('加载智能体数据失败:', err)
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 添加新智能体
   * @param input 智能体创建参数
   * @returns 返回操作结果
   */
  async function addAgent(input: CreateAgentInput): Promise<AgentOperationResult> {
    try {
      loading.value = true
      clearError()
      
      const result = await addAgentService(input)
      
      if (result.success && result.data) {
        // 添加到本地响应式数据
        agents.value.push(result.data)
        return result
      } else {
        setError(result.error || '添加智能体失败')
        return result
      }
    } catch (err) {
      const networkErr = handleApiError(err, () => addAgent(input))
      setError(networkErr.message)
      return { success: false, error: networkErr.message }
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 删除智能体
   * @param id 智能体ID
   * @returns 返回操作结果
   */
  async function deleteAgent(id: string): Promise<AgentOperationResult> {
    try {
      loading.value = true
      clearError()
      
      const result = await deleteAgentService(id)
      
      if (result.success) {
        // 从本地响应式数据中移除
        const index = agents.value.findIndex(agent => agent.id === id)
        if (index !== -1) {
          agents.value.splice(index, 1)
        }
        return result
      } else {
        setError(result.error || '删除智能体失败')
        return result
      }
    } catch (err) {
      const networkErr = handleApiError(err, () => deleteAgent(id))
      setError(networkErr.message)
      return { success: false, error: networkErr.message }
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 根据ID查找智能体
   * @param id 智能体ID
   * @returns 返回智能体数据或undefined
   */
  function findAgentById(id: string): Agent | undefined {
    return agents.value.find(agent => agent.id === id)
  }
  
  /**
   * 根据名称搜索智能体
   * @param keyword 搜索关键词
   * @returns 返回匹配的智能体列表
   */
  function searchAgents(keyword: string): Agent[] {
    if (!agents.value || !Array.isArray(agents.value)) {
      return []
    }
    
    if (!keyword.trim()) {
      return agents.value
    }
    
    const lowerKeyword = keyword.toLowerCase().trim()
    return agents.value.filter(agent => 
      agent.name.toLowerCase().includes(lowerKeyword)
    )
  }
  
  /**
   * 导出智能体数据
   * @returns 返回JSON格式的数据字符串
   */
  async function exportData(): Promise<string> {
    try {
      loading.value = true
      clearError()
      
      const result = await exportAgentsData()
      return result
    } catch (err) {
      const networkErr = handleApiError(err, exportData)
      setError(networkErr.message)
      console.error('导出数据失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 导入智能体数据
   * @param jsonData JSON格式的数据字符串
   * @returns 返回操作结果
   */
  async function importData(jsonData: string): Promise<AgentOperationResult> {
    try {
      loading.value = true
      clearError()
      
      const result = await importAgentsData(jsonData)
      
      if (result.success) {
        // 重新加载数据
        await loadAgentsData()
        return result
      } else {
        setError(result.error || '导入数据失败')
        return result
      }
    } catch (err) {
      const networkErr = handleApiError(err, () => importData(jsonData))
      setError(networkErr.message)
      return { success: false, error: networkErr.message }
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 清空所有智能体数据
   * @returns 返回操作结果
   */
  async function clearAllData(): Promise<AgentOperationResult> {
    try {
      loading.value = true
      clearError()
      
      const result = await clearAllAgents()
      
      if (result.success) {
        agents.value = []
        return { success: true, message: '数据清空成功' }
      } else {
        throw new Error(result.message || '清空数据失败')
      }
    } catch (err) {
      const networkErr = handleApiError(err, clearAllData)
      setError(networkErr.message)
      console.error('清空数据失败:', err)
      return { success: false, message: networkErr.message }
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 刷新智能体数据
   */
  async function refreshAgents() {
    await loadAgentsData()
  }
  
  // 组件挂载时自动加载数据
  onMounted(() => {
    loadAgentsData()
  })
  
  return {
    // 响应式数据
    agents,
    loading,
    error,
    
    // 网络状态
    isOnline,
    networkError,
    
    // 计算属性
    agentCount,
    hasAgents,
    sortedAgents,
    
    // 方法
    loadAgentsData,
    addAgent,
    deleteAgent,
    findAgentById,
    searchAgents,
    exportData,
    importData,
    clearAllData,
    refreshAgents,
    setError,
    clearError,
    
    // 网络相关方法
    retryRequest
  }
}